import axios, {type InternalAxiosRequestConfig,type AxiosResponse } from 'axios'

const service = axios.create({
  baseURL: process.env.VITE_API_BASE_URL, // 直接使用
  timeout: 10000
})

// 请求拦截
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers!['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截
service.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data
  },
  error => {
    return Promise.reject(error)
  }
)

// 封装GET/POST方法
export const get = <T = any>(url: string, params?: object): Promise<T> => {
  return service.get(url, { params })
}

export const post = <T = any>(url: string, data?: object): Promise<T> => {
  return service.post(url, data)
}

export default service